<!-- Flash 消息组件 -->
{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
        <div class="flash-messages">
            {% for category, message in messages %}
                <div class="alert alert-{% if category == 'error' %}danger{% elif category == 'success' %}success{% elif category == 'warning' %}warning{% else %}info{% endif %} alert-dismissible fade show" role="alert"
                     {% if category == 'success' %}data-auto-dismiss="5000"{% elif category == 'info' %}data-auto-dismiss="8000"{% endif %}>
                    <i class="bi bi-{% if category == 'error' %}exclamation-triangle{% elif category == 'success' %}check-circle{% elif category == 'warning' %}exclamation-circle{% else %}info-circle{% endif %} me-2"></i>
                    {{ message }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="关闭"></button>
                </div>
            {% endfor %}
        </div>

        <!-- 自动消失脚本 -->
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 处理自动消失的消息
            const autoHideAlerts = document.querySelectorAll('.alert[data-auto-dismiss]');
            autoHideAlerts.forEach(function(alert) {
                const delay = parseInt(alert.getAttribute('data-auto-dismiss'));
                setTimeout(function() {
                    if (alert.parentNode) {
                        // 使用Bootstrap的alert方法淡出
                        const bsAlert = new bootstrap.Alert(alert);
                        bsAlert.close();
                    }
                }, delay);
            });

            // 防止重复消息累积
            const flashContainer = document.querySelector('.flash-messages');
            if (flashContainer) {
                const alerts = flashContainer.querySelectorAll('.alert');
                // 如果消息过多，自动清理旧消息
                if (alerts.length > 3) {
                    alerts.forEach(function(alert, index) {
                        if (index < alerts.length - 3) {
                            setTimeout(function() {
                                if (alert.parentNode) {
                                    const bsAlert = new bootstrap.Alert(alert);
                                    bsAlert.close();
                                }
                            }, 1000);
                        }
                    });
                }
            }
        });
        </script>
    {% endif %}
{% endwith %}